package com.zhengshang.api.controller.pay;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.zhengshang.api.domain.AppDefaultParam;
import com.zhengshang.api.domain.AppPayRecord;
import com.zhengshang.api.service.*;
import com.zhengshang.api.task.payorder.PayOrderCollection;
import com.zhengshang.api.utils.IosVerifyUtil;
import com.zhengshang.common.annotation.RepeatSubmit;
import com.zhengshang.common.constant.app.AppConstant;
import com.zhengshang.common.core.controller.BaseController;
import com.zhengshang.common.core.domain.AjaxResult;
import com.zhengshang.common.core.domain.entity.SysRole;
import com.zhengshang.common.core.domain.model.LoginAppUser;
import com.zhengshang.common.enums.UserStatus;
import com.zhengshang.common.pay.alipay.AlipayService;
import com.zhengshang.common.utils.DateUtils;
import com.zhengshang.common.utils.uuid.IdUtils;
import com.zhengshang.security.service.SysPermissionService;
import com.zhengshang.security.service.TokenService;
import com.zhengshang.system.service.ISysConfigService;
import com.zhengshang.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.List;

/**
 *
 */
@Api(tags = "ios支付回调接口")
@RestController
@RequestMapping("/iospay")
public class IosPaysController extends BaseController {


    @Autowired
    private TokenService tokenService;
    @Autowired
    private AlipayService alipayService;
    @Autowired
    private IAppPayRecordService appPayRecordService;
    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IAppBillProductService appBillProductService;
    @Autowired
    private IAppBillRecordService appBillRecordService;
    @Autowired
    private IAppBalanceRecordService appBalanceRecordService;
    @Autowired
    private IAppBillRefundRecordService appBillRefundRecordService;


    /**
     * @throws
     * @title 获取购买星级会员签名
     * @description
     * @author admin
     * @updateTime 2021/3/25 15:50
     */
    @ApiOperation(value = "获取购买星级会员签名")
    @RepeatSubmit
    @PostMapping("/getMemSign")
    public AjaxResult getMemSign(
            HttpServletRequest request, HttpServletResponse response) {
        try {
            LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
            List<SysRole> roleList = loginAppUser.getAppUser().getRoles();
            for (SysRole sysRole : roleList) {
                if ("mem_vip".equalsIgnoreCase(sysRole.getRoleKey())) {
                    return AjaxResult.error("您已购买过VIP会员，请勿重复购买");
                }
                if ("mem_member".equalsIgnoreCase(sysRole.getRoleKey())) {
                    return AjaxResult.error("您已购买过星级会员，无需重复购买，可以升级到VIP会员");
                }
            }
            String orderNum = IdUtils.getOrdercode(AppConstant.ORDERNUM_PREFIX_MEMBER);
            AppPayRecord appPayRecord = new AppPayRecord(orderNum, DateUtils.getNowDate());
            appPayRecord.setPayType("3");
            appPayRecord.setBuyType(AppConstant.ORDERNUM_PREFIX_MEMBER);
            appPayRecord.setPayMoney(new BigDecimal(AppConstant.MEM_MEMBER));
            appPayRecord.setUserId(loginAppUser.getAppUser().getUserId());

            appPayRecord.setStatus("10");
            appPayRecord.setDelFlag(UserStatus.OK.getCode());
            appPayRecord.setCreateBy(loginAppUser.getUsername());
            appPayRecordService.insertAppPayRecord(appPayRecord);
            //先新增，再放入集合，否则没有ID
            PayOrderCollection.getOrderCollection().add(appPayRecord);
            return AjaxResult.success("购买成功", "iospay/success/" + orderNum);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("购买失败");
        }
    }

    /**
     * @title 获取购买VIP会员签名
     * @description
     * @author admin
     * @updateTime 2021/3/25 15:50
     * @throws
     */
    @ApiOperation(value = "获取购买VIP会员签名")
    @RepeatSubmit
    @PostMapping("/getVIPSign")
    public AjaxResult getVIPSign(
            HttpServletRequest request, HttpServletResponse response)
    {
        try {
            LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
            List<SysRole> roleList = loginAppUser.getAppUser().getRoles();
            for (SysRole sysRole : roleList) {
                if ("mem_vip".equalsIgnoreCase(sysRole.getRoleKey())) {
                    return AjaxResult.error("您已购买过VIP会员，请勿重复购买");
                }
            }

            String orderNum = IdUtils.getOrdercode(AppConstant.ORDERNUM_PREFIX_VIP);
//            JSONObject resultObj = analysisResult(result);
            AppPayRecord appPayRecord = new AppPayRecord(orderNum, DateUtils.getNowDate());
            appPayRecord.setPayType("3");
            appPayRecord.setBuyType(AppConstant.ORDERNUM_PREFIX_VIP);
            appPayRecord.setPayMoney(new BigDecimal(AppConstant.MEM_VIP));
            appPayRecord.setUserId(loginAppUser.getAppUser().getUserId());
            appPayRecord.setStatus("10");
            appPayRecord.setDelFlag(UserStatus.OK.getCode());
            appPayRecord.setCreateBy(loginAppUser.getUsername());
            appPayRecordService.insertAppPayRecord(appPayRecord);
            //先新增，再放入集合，否则没有ID
            PayOrderCollection.getOrderCollection().add(appPayRecord);
            return AjaxResult.success("购买成功", "iospay/success/" + orderNum);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取失败");
        }
    }


    @PostMapping("/success/{orderNum}")
    @ApiOperation("苹果内购支付返回")
    public AjaxResult iosConfirmOrder(String receipt_data, @PathVariable String orderNum) {
        //首先调用正式环境查看验证结果;
        //type:1->正式环境,发送平台验证
        String verifyResult = IosVerifyUtil.buyAppVerify(receipt_data, 1);
        if (verifyResult == null) {
            //如果验证结果不存在;提示前端;订单信息不存在;
            return AjaxResult.error("验证失败");
        }
        JSONObject job = JSONObject.parseObject(verifyResult);
        String states = job.getString("status");
        //states为21007表示,收据信息是沙盒测试用;需要请求沙盒测试地址对凭证进行校验
        if ("21007".equals(states)) {
            //如果正式环境校验不成功,则请求沙盒测试地址对凭证进行校验
            //type:0->沙盒测试,发送平台验证
            verifyResult = IosVerifyUtil.buyAppVerify(receipt_data, 0);
            job = JSONObject.parseObject(verifyResult);
            states = job.getString("status");
        }
        if (states.equals("0")) {
            // 前端所提供的收据是有效的,验证成功
            String r_receipt = job.getString("receipt");
            JSONObject returnJson = JSONObject.parseObject(r_receipt);
            String in_app = returnJson.getString("in_app");
            JSONArray jsonArray = JSONArray.parseArray(in_app);
            JSONObject in_appJson = jsonArray.getJSONObject(jsonArray.size() - 1);
            System.out.println("IOS支付验证结果3:" + in_appJson);
            //业务代码
            gateway(orderNum);
            return AjaxResult.success("支付成功");
            //支付成功
        } else {
            return AjaxResult.error("支付失败");
        }

    }

    /**
     * 支付宝回调
     */
    public void gateway(String orderNum) {

        AppPayRecord appPayRecord = appPayRecordService.selectAppPayRecordByOrderNum(orderNum);
        if (appPayRecord != null) {
            appPayRecord.setStatus("20");
            appPayRecordService.updateAppPayRecord(appPayRecord);
            PayOrderCollection.remove(orderNum);
            LoginAppUser loginAppUser = tokenService.getLoginAppUser(appPayRecord.getUserId());
            switch (appPayRecord.getBuyType()) {
                //购买星级会员
                case AppConstant.ORDERNUM_PREFIX_MEMBER:
                    loginAppUser.getAppUser().setAppMemberType("2");
                    loginAppUser = userService.updateRole(loginAppUser, "mem_member");
                    break;
                //购买VIP
                case AppConstant.ORDERNUM_PREFIX_VIP:
                    loginAppUser.getAppUser().setAppMemberType("3");
                    loginAppUser = userService.updateRole(loginAppUser, "mem_vip");
                    userService.thawCommission(loginAppUser.getAppUser());//解冻被冻结的佣金
                    break;
            }
            //更新上级及上上级用户余额
            userService.buyMember(
                    loginAppUser.getAppUser(),
                    loginAppUser.getAppUser().getUpUserId(),
                    appPayRecord.getBuyType(),
                    new AppDefaultParam(configService.selectConfigByKey("app.buyvip.up.bonus"), configService.selectConfigByKey("app.buyvip.upup.bonus"), configService.selectConfigByKey("app.buymem.up.bonus"))
            );
            loginAppUser.setPermissions(permissionService.getMenuPermission(loginAppUser.getAppUser()));
            tokenService.refreshToken(loginAppUser);

        }
    }

}
